package com.ht.mt.sric.util;

import java.util.HashMap;
import java.util.Hashtable;
import java.util.logging.Logger;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class ServiceLocator {
    
    private Logger LOG = Logger.getLogger(ServiceLocator.class.getName());
        private static final String JNDI_BASE_ENTRY = "java:comp/env/ejb/";
        private Hashtable<String, Object> caching = new Hashtable<String, Object>(5);
        private static ServiceLocator serviceLocator = null;
        HashMap serviceCache = null;
        InitialContext context = null;
        
    public ServiceLocator() {
        try {
                    serviceCache = new HashMap();
                    context = new InitialContext();
                } catch (Exception e) {
                    e.printStackTrace();
                }
    }
    
    public static ServiceLocator getInstance() throws NamingException {
            if (serviceLocator == null) {
                serviceLocator = new ServiceLocator();
            }
            return serviceLocator;
        }
    
    public Object findService(String name) {
            try {
                Object objRef;
                if (null == (objRef = caching.get(name))) {
                    InitialContext ic = new InitialContext();
                    objRef = ic.lookup(JNDI_BASE_ENTRY + name);
                    caching.put(name, objRef);
                }
                return objRef;
            } catch (NamingException e) {
                LOG.severe(e.getMessage());
            }
            return null;
        }
    
    public Object getFacadeService(String jndiName) throws NamingException {
           if (!serviceCache.containsKey(jndiName)) {
               serviceCache.put(jndiName, context.lookup("java:comp/env/ejb/" + jndiName));
           }
           return serviceCache.get(jndiName);
       }


       public Object findServiceRemote(String name) {
           Object objRef = null;
           try {
               final Context context = getInitialContext();
               objRef = context.lookup(name + "SessionEJBBean#com.ht.mt.sric.sesion.remota." + name + "SessionEJBBeanRemote");
           } catch (Exception ex) {
               ex.printStackTrace();
           }
           return objRef;
       }

       //inicio-bpm

       private Context getInitialContext() throws NamingException, ExceptionHandler {
           Hashtable env = new Hashtable();
           // Estableciendo el contexto inicial para GlassFish
           env.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
           env.put(Context.PROVIDER_URL, "t3://127.0.0.1:7101");
           return new InitialContext(env);
       }

}
